# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:

import pymysql
import hashlib

class GetCarsInfoCollection(object):
    ''''''
    def __init__(self, **kwargs):
        self.src_db = kwargs.get("src_db")
        self.dest_db = kwargs.get("dest_db")
        self.insert_table = kwargs.get("insert_table")
        self.src_conn, self.src_curs = self.get_conn_curs(db_config=self.src_db, type='dict')
        self.dest_conn, self.dest_curs = self.get_conn_curs(db_config=self.dest_db, type='dict')
        self.num = 0

    def get_md5(self, str):
        '''获取md5加密电子指纹'''
        md5 = hashlib.md5()
        md5.update(str)
        return md5.hexdigest()

    def get_conn(self, dbconfig_dict):
        conn = pymysql.connect(**dbconfig_dict)
        return conn

    def get_cursor(self, conn, type='stream'):
        if type == 'stream':
            return conn.cursor(pymysql.cursors.SSCursor)  # 返回流式游标,查询大量数据时不占用内存(返回数据形式是元组)
        elif type == 'dict':
            return conn.cursor(pymysql.cursors.DictCursor)  # 返回字典形式游标,查询出的数据以字典形式返回
        elif type == 'default':
            return conn.cursor()
        else:
            raise Exception("cursor type error")

    def get_conn_curs(self, db_config, type='stream'):

        conn = self.get_conn(db_config)
        curs = self.get_cursor(conn, type=type)
        return conn,curs

    def construct_insert_sql(self, table, data, db=None):
        '''传入表名, 数据字典, 返回insert语句'''
        fields = '`' + '`,`'.join(data.keys()) + '`'
        values = []
        for v in data.values():
            if v == 0:
                v = '0'
            elif not v:
                v = ''
            if type(v) == int:# or type(v) == long:
                values.append(v.__str__())
            elif v == "now()":
                values.append(v)
            else:
                values.append("'%s'" % v.replace("'", " ").replace("\\", "\\\\"))
        if db:
            sql = 'INSERT INTO `%s`.`%s` (%s) VALUES (%s)' % (db, table, fields, ",".join(values))
        else:
            sql = 'INSERT INTO `%s` (%s) VALUES (%s)' % (table, fields, ",".join(values))
        return sql

    def get_cid_list(self):
        sql = '''select distinct f2 from destcnt where status="1"'''
        self.src_curs.execute(sql)
        data = self.src_curs.fetchall()
        return [i.get("f2") for i in data]

    def get_info(self, cid):
        sql = '''select * from destcnt where f2="{}" and status="1";'''.format(cid)
        # print(sql)
        self.src_curs.execute(sql)
        data = self.src_curs.fetchone()
        name = data.get("f3").strip()
        time1 = data.get("f4").replace(' ', '')
        time2 = data.get("f5").replace(' ', '')
        # print(name, time1, time2)
        return name, time1, time2

    def run(self):
        cid_list = self.get_cid_list()
        for cid in cid_list:
            # print(cid)
            name, limit1, limit2 = self.get_info(cid)
            md5_str = (name+limit1+limit2+cid).encode('utf8')
            # print(md5_str)
            uid = self.get_md5(md5_str)
            brand = 'nissan'
            brandCode = 'nissan'
            condition = limit1+'-'+limit2
            _dict = dict(
                uid=uid,
                name=name,
                brand=brand,
                brandCode=brandCode,
                condition=condition,
                limit='',
                limit2='',
                limit3='',
                limit4='',
                label='',
                code=cid,
                description='',
                imagePath='',
                imgName='',
                extra_info='',
                updatetime='now()',
                createtime='now()'
            )
            insert_sql = self.construct_insert_sql(self.insert_table, _dict)
            print(insert_sql)
            self.dest_curs.execute(insert_sql)
            self.num += 1
            if self.num % 100 == 0:
                self.dest_conn.commit()
                print("提交insert缓存, 当前数量: {}".format(self.num))
        self.dest_conn.commit()
        print("提交最终缓存, 总数据量: {}".format(self.num))


        # 获取所有cid
        # 遍历cid,并且获取cid对应的车系名,生产时间
if __name__ == '__main__':
    src_db = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="nissan_new",
        charset="utf8",
    )
    dest_db = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="nissan_new",
        charset="utf8",
    )
    insert_table = 'cars_info_collection'
    tools = GetCarsInfoCollection(src_db=src_db, dest_db=dest_db, insert_table=insert_table)
    tools.run()